import axios from 'axios'
import {Modal} from 'view-design'
import {getToken, removeToke, getLanguage, removeCurrentUser, localRemove} from '@/libs/util'

export function fetch(options) {
    let data = null
    if (options.contentType == 'application/json') {
        data = options.params
    } else if (options.hasOwnProperty('formData')) {
        data = new FormData()
        Object.keys(options.formData).forEach(item => {
            data.append(item, options.formData[item])
        })
    }

    return new Promise((resolve, reject) => {
        let header = {
          Authorization: getToken() || '',
          locale: getLanguage(),
          'Content-Type': options.contentType || 'application/x-www-form-urlencoded;charset=UTF-8', // 'multipart/form-data'
        }
        axios({
            method: options.method || 'post',
            url: options.url,
            data: data || options.data,
            params: options.params,
            headers: header,
            timeout: 20 * 1000
        }).then(res => {
            if (res.data.errorCode === '31' || res.data.errorCode === '34' || res.data.errorCode === '28') {
                removeToke()
                removeCurrentUser()
                localRemove("routeTree")
                window.location.reload()
            } else if (res.data.errorCode === '401' || res.data.errorCode === '403') {
                Modal.confirm({
                    title: res.data.errorMsg,
                    content: res.data.errorMsg || this.$t('login.info'),
                    onOk: () => {
                        removeToke()
                        removeCurrentUser()
                        localRemove("routeTree")
                        window.location.reload()
                    },
                    onCancel: () => {
                        removeToke()
                        removeCurrentUser()
                        localRemove("routeTree")
                        window.location.reload()
                    }
                })
            } else {
                if (res.data.result == true || res.data.result == false) {
                    resolve(res.data)
                } else {
                    resolve(res)
                }

            }
        }).catch(error => {
            console.error('接口请求异常：' + error)
            reject(error)
        })
    })
}
